function [ll, grad] = T2ParametersLL_m( par, x, echoes, sigma)

% computes the likelihood of the rice distributed inversion recovery data
% echoes = inversion times [n x 1] vector
% par = the 2 element parametervector [A, R1]
%
% The datamodel is given by
% M = A*exp( - TE * R1) 
%
% Created by Henk Smit, EMC, 01-2011 based on the work by Dirk Poot,
% University of Antwerp, 13-8-2007

if size(par,1) ~= 2% + (nargin<=3)  HENK
    error('incorrect parameter vector');
end;
numtr = size(par,2);
if nargin<=3
    sigma = par(3,:); %HENK
end;
numgr = size(echoes,1); %numTEs
if ((size(x,1)~=numgr || size(x,2)~=numtr) && ~isempty(x)) || size(echoes,2)~=1  || numel(sigma)~=1
    error('incorrect size in input.');
end;

A = zeros(numgr,numtr);
A_ex = zeros(numgr,numtr);

for k=1:numtr   
    A_ex(:,k) = exp(-echoes(:,1)*par(2,k));
    A(:,k) = par(1,k) * A_ex(:,k);
    
end;

if isempty(x)
    ll = A;
    return;
end;

if nargout>1
    [lrpdf, ricegrad] = logricepdf(x, A, sigma,logical([0 1 nargin<=3]));
    dAdpar=[A_ex(:) -repmat(echoes,numtr,1) .* A(:)]; %HENK 
    grad = reshape(-sum( reshape( ricegrad(:,ones(1,2)).*dAdpar, numgr, numtr * 2) ), numtr, 2);%HENK
    grad = grad';  
else
    [lrpdf] = logricepdf(x, A, sigma );
end;
ll = - sum( lrpdf(:) );
